import axios from './http'
import { Canceler, AxiosResponse } from 'axios'
type TReqObj = {
  [K in string]?: Canceler
}
type TFun<U extends Object> = (T: string, U: U) => Promise<AxiosResponse<any, any>> | null
const limitSameReq = () => {
  const reqObj: TReqObj = {}
  const req: TFun<any> = (url: string = '', data = {}) => {
    let completeUrl = url + '?'
    if (data) {
      const entryArr = Object.entries(data)
      completeUrl += entryArr.map(item => item.join('=')).join('&')
    }
    if (reqObj[completeUrl]) {
      reqObj[completeUrl]!()
      return null
    }
    return axios
      .get(url, {
        params: data,
        cancelToken: new axios.CancelToken((c: Canceler) => {
          reqObj[completeUrl] = c
        })
      })
      .finally(() => {
        delete reqObj[completeUrl]
      })
  }
  return req
}
const limitSameReqGet = limitSameReq()
export { limitSameReqGet }
